require('dotenv').config();
const fs = require('fs');
const express = require('express');
const pug = require('pug');
const path = require('path');
const sizeOf = require('image-size');
const getLocalIp = require('./script/utils/get-local-ip')
const app = express();

const livereload = require('livereload');
const liveReloadServer = livereload.createServer({
  port: 35729,  // 显式指定端口
  exts: ['pug', 'json', 'js']  // 包含需要监听的扩展类型
});
liveReloadServer.watch([__dirname + "/projects"]);

// 更新includes
const updateIncludes = require('./script/utils/update-includes.js');
updateIncludes()

// 自动更新客户端
const connectLivereload = require('connect-livereload');
app.use(connectLivereload())

app.set('view engine', 'pug');
app.set('views', [path.join(__dirname, 'src/pug'), __dirname]);
app.use(express.static('assets'));

// 静态资源（保持原样）
app.use('/assets', express.static('assets'));

// 动态路由处理
app.get('/:project', (req, res) => {
  const projectPath = path.join(__dirname, 'projects', req.params.project);
  // 动态配置静态资源
  app.use('/images', express.static(path.join(projectPath, 'images')));

  let urls = []
  let images = []

  // 检查 urls.json 文件是否存在
  const urlsPath = path.join(projectPath, 'urls.json');
  if (fs.existsSync(urlsPath)) {
    urls = require(urlsPath);
    const hasUrls = Array.isArray(urls) && urls.length > 0
    images = urls.map(img => ({ ...img, url: `images/${img.file}` }))
  }

  const attrs = require(path.join(__dirname, 'src/data', 'attrs.json'));
  const audiFooterUrls = require(path.join(__dirname, 'src/data', 'audi.json'));
  const fordFooterUrls = require(path.join(__dirname, 'src/data', 'ford.json'));
  const mockUrls = require(path.join(__dirname, 'src/data', 'mock.json'));

  const audiUrls = Object.entries(audiFooterUrls)
    .reduce((acc, [key, value]) => {
      if (value.file) { acc[key] = { ...value, url: value.file } }
      return acc;
    }, {});


  const fordUrls = Object.entries(fordFooterUrls)
    .reduce((acc, [key, value]) => {
      if (value.file) { acc[key] = { ...value, url: value.file } }
      return acc;
    }, {});


  // 检查 home.pug 文件是否存在
  if (!fs.existsSync(path.join(projectPath, 'home.pug'))) {
    return res.send(`project ${req.params.project} not exist`);
  }

  // 设置渲染数据
  const templateData = { images, audiUrls, fordUrls, mockUrls, ...attrs }
  // res.set('Refresh', '1'); // 设置0秒后刷新页面
  res.render(path.join(projectPath, 'home.pug'), templateData);
});

app.get('/samples/:sample', (req, res) => {
  const samplePath = path.join(__dirname, 'samples', req.params.sample);
  const mockData = require('./src/data/mock.json');

  // 动态配置项目资源
  const { resolve } = require('path');
  const samplesDir = resolve(__dirname, 'samples');

  // 检查 home.pug 文件是否存在
  if (!fs.existsSync(samplePath)) {
    return res.send(`Sample <b>[${req.params.sample}]</b> not exist`);
  }

  fs.readdirSync(samplesDir).forEach(project => {
    const imagesPath = path.join(samplesDir, project, 'images');
    app.use(`/${project}/images`, express.static(imagesPath));
    app.use('./', express.static('assets'));
  });

  res.render(path.join(samplePath, 'home.pug'), { images: mockData });
});


// 配置热更新
if (process.env.NODE_ENV !== 'production') {
  app.locals.pretty = true;
  app.disable('view cache');
}


// 启动服务
app.listen(3333, () => {
  // console.log(`Server running at ${getLocalIp()} on port 3333`);
  console.log(`Server running at http://${getLocalIp()}:3333/`);
});
